﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Text;
using System.Threading;

namespace LPBToolsLib
{
    public class StationsOnline
    {
        public int StationTimeOutSecond { get; set; } = 60;

        private Mutex tMutex = new Mutex(false, "StationsOnline" + Guid.NewGuid().ToString());
        public Dictionary<string, StationInfo> tStationList { get; } = new Dictionary<string, StationInfo>();

        public StationInfo getStation(string StaToken)
        {
            if ((!string.IsNullOrEmpty(StaToken)) && tStationList.ContainsKey(StaToken))
            {
                return tStationList[StaToken];
            }
            return null;
        }

        /// <summary>
        /// 刷新工作站最后工作时间，成功刷新后返回工作站节点信息
        /// 注意：如果工作站超时，将会被删除
        /// </summary>
        /// <param name="StaToken"></param>
        /// <returns></returns>
        public StationInfo reflashStation(string StaToken)
        {
            if ((!string.IsNullOrEmpty(StaToken)) && tStationList.ContainsKey(StaToken))
            {
                StationInfo tDestStation = tStationList[StaToken];
                if (tDestStation != null)
                {
                    TimeSpan tLastAct = DateTime.Now - tDestStation.LastAction;
                    if (tLastAct.TotalSeconds < StationTimeOutSecond)
                    {
                        tStationList[StaToken].LastAction = DateTime.Now;
                        tStationList[StaToken].LastSecond = StationTimeOutSecond;
                        return tStationList[StaToken];
                    }
                    else
                    {
                        tMutex.WaitOne();
                        try
                        {
                            tStationList.Remove(StaToken);
                        }
                        finally
                        {
                            tMutex.ReleaseMutex();
                        }
                    }
                }
            }
            return null;
        }

        public StationInfo createNewStation(StationInfo tDestStation)
        {
            StationInfo tStation = null;
            if (tDestStation != null)
            {
                tStation = reflashStation(tDestStation.Token);
                if (tStation == null)
                {
                    tStation = tDestStation;
                    tDestStation.LastAction = DateTime.Now;
                    tMutex.WaitOne();
                    try
                    {
                        tStationList.Add(tDestStation.Token, tDestStation);
                        tDestStation.LastSecond = StationTimeOutSecond;
                    }
                    finally
                    {
                        tMutex.ReleaseMutex();
                    }
                }
            }
            return tStation;
        }

        /// <summary>
        /// 获得当前在线工作站清单
        /// 注意：同时将清理不在线清单
        /// </summary>
        /// <param name="tStaList"></param>
        /// <returns></returns>
        public int getOnlineStaList(List<StationInfo> tStaList)
        {
            tStaList.Clear();
            List<string> tDelS = new List<string>();
            if (tStationList.Count > 0)
            {
                foreach (KeyValuePair<string, StationInfo> item in tStationList)
                {
                    StationInfo tDestStation = item.Value;
                    if (tDestStation != null)
                    {
                        TimeSpan tLastAct = DateTime.Now - tDestStation.LastAction;
                        if (tLastAct.TotalSeconds < StationTimeOutSecond)
                            tStaList.Add(item.Value);
                        else
                            tDelS.Add(item.Key);
                    }
                    if (tDelS.Count > 0)
                    {
                        tMutex.WaitOne();
                        try
                        {
                            foreach (string sDelKey in tDelS)
                                tStationList.Remove(sDelKey);
                        }
                        finally
                        {
                            tMutex.ReleaseMutex();
                        }
                    }
                    return tStaList.Count;
                }
            }
            return 0;
        }
    }
    /// <summary>
    /// 工作站运行信息对象
    /// 仅为基础结果，具体需要为基础进行继承
    /// </summary>
    public class StationInfo: RecordBase
    {
        public DateTime CreateTime { get; } = DateTime.Now;
        /// <summary>
        /// 工作站运行的令牌
        /// 使用过程中不可修改
        /// </summary>
        public string Token { get; private set; } = Guid.NewGuid().ToString("N").ToUpper();
        /// <summary>
        /// 工作站最后活动时间
        /// </summary>
        public DateTime LastAction { get; set; } = DateTime.Now;
        /// <summary>
        /// 工作站ID
        /// 使用过程中不可修改
        /// </summary>
        public int ID { get; private set; } = 0;
        /// <summary>
        /// 工作站具体信息结构体
        /// 使用过程中不可修改
        /// </summary>
        private object tDatas { get; set; } = "";

        /// <summary>
        /// 剩余保持时长
        /// </summary>
        public int LastSecond { get; set; } = 0;
        public object Datas { get { return tDatas; } }
        public StationInfo(string DestJSONValues) : base(DestJSONValues)
        {
        }
        public StationInfo(Dictionary<string, object> Detail) : base(JsonConvert.SerializeObject(Detail))
        {
        }
        public StationInfo(int DestID, object DestDatas):base("")
        {
            ID = DestID;
            tDatas = DestDatas;
        }
             
    }
    public enum StaActionType
    {
        None = 0,
        Login,
        Logout,
        LostConnection,
    }
}
